/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hiruss.efair.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.hiruss.efair.entities.Advertisement;
import com.hiruss.efair.persistence.AdvertisementManager;

/**
 * 
 * @author Hiru
 */
public class AddAdvertisementServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2993067360578797889L;
	/**
	 * 
	 */
	private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);

		String itemId = req.getParameter("item");
		long timeStamp = new Date().getTime();
		
		Advertisement ad = new Advertisement();
		ad.setAddId(timeStamp + "-" + itemId.toLowerCase().replaceAll("[^a-z0-9]", ""));
		ad.setApproved(false);
		ad.setCategory(req.getParameter("category"));
		ad.setItem(req.getParameter("item"));
		ad.setDescription(req.getParameter("description"));
		ad.setDimensions(req.getParameter("dimensions"));
		ad.setPaid(false);
		ad.setPiority(1);
		ad.setPrice(Double.parseDouble(req.getParameter("price")));
		ad.setSellerContactNum(req.getParameter("sellerContactNum"));
		ad.setSellerEmail(req.getParameter("sellerEmail"));
		ad.setSellerName(req.getParameter("sellerName"));
		ad.setWeight(req.getParameter("weight"));
		
		
		List<BlobKey> datasheet = blobs.get("datasheet");
		if(datasheet != null){
			ad.setDatasheet(datasheet.get(0).getKeyString());
		}
		List<BlobKey> images = blobs.get("images");
		if(images != null){
			List<String> imageKeys = new ArrayList<String>();
			for(BlobKey image : images){
				imageKeys.add(image.getKeyString());
			}
			ad.setImages(imageKeys);
		}
		
		AdvertisementManager adm = new AdvertisementManager();
		adm.addAdvertisement(ad);
		req.getRequestDispatcher("/gateway.jsp").forward(req, resp);
		
	}
}
